import 'package:getx_scaffold/getx_scaffold.dart';
import 'exchange_records_state.dart';
import '../../../core/repository/default_api.dart';
import '../../../core/config/api_config.dart';

class ExchangeRecordsLogic extends GetxController {
  final state = ExchangeRecordsState();
  final _api = DefaultApi();

  @override
  void onInit() {
    super.onInit();
    _loadExchangeRecords();
  }

  /// 加载兑换记录
  Future<void> _loadExchangeRecords() async {
    try {
      state.isLoading.value = true;
      final response = await _api.queryShopPointsOrdersGet<Map<String, dynamic>>(
        pageNum: 1,
        pageSize: 100,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final List<dynamic> rows = response['rows'] ?? [];
        state.exchangeRecords.value = rows.map((item) {
          final shopProducts = item['shopProducts'];
          
          // 获取第一张图片URL
          String? imageUrl;
          if (shopProducts != null && shopProducts['imageUrl'] != null) {
            final images = shopProducts['imageUrl'].toString().split(',');
            if (images.isNotEmpty) {
              imageUrl = images[0].trim();
              if (!imageUrl.startsWith('http')) {
                imageUrl = '${ApiConfig.baseUrl}$imageUrl';
              }
            }
          }

          return {
            'id': item['id'],
            'orderNo': item['orderNo'],
            'productName': shopProducts?['name'] ?? '',
            'quantity': item['productCount'] ?? 1,
            'points': item['actualPoints'] ?? 0,
            'status': _mapOrderStatus(item['status']),
            'time': item['createdAt'] ?? '',
            'image': imageUrl,
            'productsId': item['productsId'],
            'addressId': item['addressId'],
          };
        }).toList();
      }
    } catch (e) {
      Toast.show('加载兑换记录失败');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 映射订单状态
  String _mapOrderStatus(dynamic status) {
    // 根据实际API返回的状态值进行映射
    // 这里假设API返回的是数字状态码
    switch (status) {
      case 0:
        return 'pending_payment'; // 待付款
      case 1:
        return 'pending_shipment'; // 待发货
      case 2:
        return 'pending_receipt'; // 待收货
      case 3:
        return 'completed'; // 已完成
      default:
        return 'pending_payment';
    }
  }

  /// 切换tab
  void changeTab(int index) {
    state.selectedTabIndex.value = index;
  }

  /// 获取过滤后的记录
  List<Map<String, dynamic>> get filteredRecords {
    final index = state.selectedTabIndex.value;
    if (index == 0) {
      // 待付款
      return state.exchangeRecords.where((r) => r['status'] == 'pending_payment').toList();
    } else if (index == 1) {
      // 待发货
      return state.exchangeRecords.where((r) => r['status'] == 'pending_shipment').toList();
    } else if (index == 2) {
      // 待收货
      return state.exchangeRecords.where((r) => r['status'] == 'pending_receipt').toList();
    } else {
      // 已完成
      return state.exchangeRecords.where((r) => r['status'] == 'completed').toList();
    }
  }

  /// 查看物流
  void viewLogistics(Map<String, dynamic> record) {
    Get.toNamed('/logistics-detail', arguments: record);
  }

  /// 查看订单详情
  Future<void> viewOrderDetail(int orderId) async {
    try {
      final response = await _api.queryShopPointsOrderDetailGet<Map<String, dynamic>>(
        id: orderId,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        final orderData = response['data'];
        // 跳转到订单详情页面（这里暂时跳转到物流详情页面，后续可以创建专门的订单详情页面）
        Get.toNamed('/logistics-detail', arguments: orderData);
      }
    } catch (e) {
      Toast.show('加载订单详情失败');
    }
  }

  /// 获取状态文本
  String getStatusText(String status) {
    switch (status) {
      case 'pending_payment':
        return '待付款';
      case 'pending_shipment':
        return '待发货';
      case 'pending_receipt':
        return '待收货';
      case 'completed':
        return '已完成';
      default:
        return '';
    }
  }
}
